package com.gitee.poi.plugin.util;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;

/**
 * @author wangxin
 * @time 2018/10/29 14:57
 */
public class ClassUtils {

    /**
     * 获取该类及其父类所有字段
     * @param clazz
     * @return
     */
    public static Field[] getAllField(Class clazz){
        return getAllField(clazz,Object.class);
    }

    public static Field[] getAllField(Class clazz,Class endClazz){
        if(clazz == endClazz) return new Field[0];
        Field[] superFields = getAllField(clazz.getSuperclass(),endClazz);
        Field[] declaredFields = clazz.getDeclaredFields();
        Field mergerField[] = new Field[superFields.length+declaredFields.length];
        System.arraycopy(superFields,0,mergerField,0,superFields.length);
        System.arraycopy(declaredFields,0,mergerField,superFields.length,declaredFields.length);
        return mergerField;
    }

    /**
     * 判断是否是可直接写入的类
     * @param clazz
     * @return
     */
    public static boolean isWriteClass(Class<?> clazz){
        if(CharSequence.class.isAssignableFrom(clazz)) return true;
        if(Number.class.isAssignableFrom(clazz)) return true;
        if(clazz.isPrimitive()) return true;
        if(Date.class.isAssignableFrom(clazz)) return true;
        return false;
    }

    public static boolean isCollection(Class<?> clazz){
        return Collection.class.isAssignableFrom(clazz);
    }

    public static Class getCollectionComponentClass(Field field){
        ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        return (Class) parameterizedType.getActualTypeArguments()[0];
    }

    public static Type[] getComponentClass(Field field){
        ParameterizedType parameterizedType = (ParameterizedType) field.getGenericType();
        return parameterizedType.getActualTypeArguments();
    }
}
